# -*- coding: utf-8 -*-

# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals
import random
import time
from db import RedisServer
from api import export
from infoLog import logger
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

class HalfSpiderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, dict or Item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Request, dict
        # or Item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class HalfDownloaderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        return None

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)

class RandomUserAgent(object):
    def __init__(self,ua):
        self.ua = ua

    @classmethod
    def from_crawler(cls,crawler):
        return cls(
            ua=crawler.settings.get('USER_MAP')
        )

    def process_request(self,request,spider):
        this_ua = random.choice(self.ua)
        request.headers['User-Agent'] = this_ua
        # print(this_ua)

class ProxyMiddleWare(object):
    def __init__(self):
        self.rs = RedisServer()

    def avail_count_add(self):
        if self.rs.count() < 50:
            export()
            time.sleep(1)

    def score_assert(self,ip):
        if self.rs.score(ip) <= 0:
            print(f'{ip}--------->delete')
            return self.rs.delete(ip)

    def process_request(self,request,spider):
        self.avail_count_add()
        this_ip = self.rs.random()
        request.meta['proxy'] = this_ip

    def process_response(self, request, response, spider):
        '''
        :param request:
        :param response: 操作太频繁了，请先歇一歇。
        :param spider:
        :return:
        '''
        work_ip = request.meta['proxy']
        # res_content = response.body.decode('gbk','ignore')
        res_content = response.text
        if '²Ù×÷Ì«Æµ·±ÁË£¬ÇëÏÈÐªÒ»Ðª¡£' in res_content:
            self.rs.incrby(work_ip,-1)
            print(f'ip:{work_ip}访问受限，当前分数值为{self.rs.score(work_ip)}')
            self.score_assert(work_ip)
            return request
        return response

    def process_exception(self,request,exception,spider):
        '''
        :param request:
        :param exception: 1.User timeout caused connection failure. 2.urllib3.exceptions.MaxRetryError: HTTPConnectionPool. 3.Connection was refused by other side: 10061
        :param spider:
        :return:
        '''
        if ('User timeout' or '1006') in str(exception):
            work_ip = request.meta['proxy']
            self.rs.incrby(work_ip,-2)
            print(work_ip + '超时')
            self.score_assert(work_ip)
        return request